package ad_exercise_4.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * 
 * @author Sjaak Smetsers (number?)
 */
public class LZWNaive {
	
	private HashMap<String, Integer>	codeTable;
	public int							FIRST_CODE	= 256, MAX_CODE = 4096;
	
	private int							nextCode	= FIRST_CODE;
	
	private String intToString(int ic) {
		return String.format("%c", (char) ic);
	}
	
	public LZWNaive() {
		codeTable = new HashMap<String, Integer>();
		for (int i = 0; i < FIRST_CODE; i++) {
			codeTable.put(intToString(i), i);
		}
	}
	
	public void compress(InputStream input) throws IOException {
		int next = input.read();
		String prefix = intToString(next);
		do {
			next = input.read();
			if (next != -1) {
				String new_prefix = prefix + (char) next;
				if (codeTable.containsKey(new_prefix)) {
					prefix = new_prefix;
				} else {
					// System.out.println(codeTable.get(prefix));
					if (nextCode < MAX_CODE) {
						codeTable.put(new_prefix, nextCode);
						nextCode++;
					}
					prefix = intToString(next);
				}
			}
		} while (next != -1);
		// System.out.println(codeTable.get(prefix));
	}
}
